import { NavBar, InfiniteScroll } from 'antd-mobile'
import { useHistory, useParams } from 'react-router-dom'
import classNames from 'classnames'
import styles from './index.module.scss'

import Icon from '@/components/Icon'
import CommentItem from './components/CommentItem'
import CommentFooter from './components/CommentFooter'
import { getArticle } from '@/store/action/article'
import dayjs from 'dayjs'
import { useInitialState } from '@/utils/hooks'
import DOMpurify from 'dompurify'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import { useEffect, useRef, useState } from 'react'

const Article = () => {
  const history = useHistory()
  const { id } = useParams<{ id: string }>()
  const { info } = useInitialState(() => getArticle(id), 'article')
  useEffect(() => {
    // 配置hljs
    hljs.configure({
      // 忽略未转义字符
      ignoreUnescapedHTML: true,
    })
    const codes = document.querySelectorAll('.dg-html pre code')
    codes.forEach((e) => {
      hljs.highlightElement(e as HTMLElement)
    })
  }, [])
  const [isShowAuthor, setIsShowAuthor] = useState(false)
  const wrapperRef = useRef<HTMLDivElement>(null)
  const authorRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    const wrapDOM = wrapperRef.current!
    const authDOM = authorRef.current!
    const onScroll = function () {
      const rect = authDOM.getBoundingClientRect()
      // console.log(rect.top)

      if (rect.top <= 0) {
        setIsShowAuthor(true)
      } else {
        setIsShowAuthor(false)
      }
    }
    wrapDOM.addEventListener('scroll', onScroll)
    return () => {
      wrapDOM.removeEventListener('scroll', onScroll)
    }
  }, [])

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <Icon type="icongengduo" />
            </span>
          }
        >
          {isShowAuthor && (
            <div className="nav-author">
              <img src={info.aut_photo} alt="" />
              <span className="name">{info.aut_name}</span>
              <span
                className={classNames(
                  'follow',
                  info.is_followed ? 'followed' : ''
                )}
              >
                {info.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {/* 文章详情和评论 */}
        <div className="wrapper" ref={wrapperRef}>
          <div className="article-wrapper">
            <div className="header">
              <h1 className="title">{info.title}</h1>

              <div className="info">
                <span>{dayjs(info.pubdate).format('YYYY-MM-DD')}</span>
                <span>{info.read_count} 阅读</span>
                <span>{info.comm_count} 评论</span>
              </div>

              <div className="author" ref={authorRef}>
                <img src={info.aut_photo} alt="" />
                <span className="name">{info.aut_name}</span>
                <span
                  className={classNames(
                    'follow',
                    info.is_followed ? 'followed' : ''
                  )}
                >
                  {info.is_followed ? '已关注' : '关注'}
                </span>
              </div>
            </div>

            <div className="content">
              <div
                className="content-html dg-html"
                dangerouslySetInnerHTML={{
                  __html: DOMpurify.sanitize(info.content || ''),
                }}
              />
              <div className="date">
                发布文章时间：{dayjs(info.pubdate).format('YYYY-MM-DD')}
              </div>
            </div>
          </div>

          <div className="comment">
            <div className="comment-header">
              <span>全部评论（{info.comm_count}）</span>
              <span>{info.like_count} 点赞</span>
            </div>

            <div className="comment-list">
              <CommentItem />

              <InfiniteScroll
                hasMore={false}
                loadMore={async () => {
                  console.log(1)
                }}
              />
            </div>
          </div>
        </div>

        {/* 底部评论栏 */}
        <CommentFooter />
      </div>
    </div>
  )
}

export default Article
